#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    pid_t id = fork();
    pid_t rid;
    if (id == 0)
    {
        int cnt = 5;
        while(cnt--)
        {
            printf("子进程正在运行中, pid: %d\n",getpid());
            sleep(1);
        }
        exit(100);
    }
    else if(id > 0)
    {
       // rid = wait(nullptr);
        int status = 0;
        rid = waitpid(id,&status,0);
        if (rid > 0)
        {
            printf("wait process: %d, status: %d\n",rid,(status>>8)&0xFF);
        }
        else if(rid < 0)
        {
            perror("waitpid");
        }
        while(1)
        {
            printf("正在等待子进程结束\n");
            sleep(1); 
        }
    }
    return 0;
}




//int main(int argc, char *argv[])
//{
//    pid_t cpid, w;
//    int status;
//
//    cpid = fork();
//    if (cpid == -1) {
//        perror("fork");
//        exit(EXIT_FAILURE);
//    }
//
//    if (cpid == 0) {            /* Code executed by child */
//        printf("Child PID is %ld, argc: %d\n", (long) getpid(),argc);
//        if (argc == 1)
//            pause();                    /* Wait for signals */
//        _exit(atoi(argv[1]));
//
//    } else {                    /* Code executed by parent */
//        do {
//            w = waitpid(cpid, &status, WUNTRACED | WCONTINUED);
//            printf("i am a process pid: %d\n", w);
//            //w = waitpid(cpid, &status, WUNTRACED | WCONTINUED);
//            printf("kill process is : %d\n", w);
//            if (w == -1) {
//                perror("waitpid");
//                exit(EXIT_FAILURE);
//            }
//            if (WIFEXITED(status)) {
//                printf("exited, status=%d\n", WEXITSTATUS(status));
//            } else if (WIFSIGNALED(status)) {
//                printf("killed by signal %d\n", WTERMSIG(status));
//            } else if (WIFSTOPPED(status)) {
//                printf("stopped by signal %d\n", WSTOPSIG(status));
//            } else if (WIFCONTINUED(status)) {
//                printf("continued\n");
//            }
//        } while (!WIFEXITED(status) && !WIFSIGNALED(status));
//        printf("exited, status=%d\n", WEXITSTATUS(status));
//        exit(EXIT_SUCCESS);
//    }
//}

